﻿using HomagChina.Basic.CCT.Db.CCT_Db;
using HomagChina.Basic.CCT.PLC;
using HomagChina.OpcService_CNC;
using HomagGroup.Base.Communication.Items;
using System;
using System.Linq;
using System.Threading;
using HomagGroup.UnifiedCommunication.Client.Toolkit;
using HomagGroup.UnifiedCommunication.Common;
using HomagGroup.UnifiedCommunication;

namespace Proxy
{
    public class InfeedTransportHandle
    {
        InsertInfoHandle Handle_Insert;
        SearchInfoHandle Handle_Search;
        ModifyInfoHandle Handle_Modify;
        CommonHandle Handle_Common;
        PlcHandle Handle_Plc;
        OpcService_CNC OpcService_CNC;
        const string Description = "NcCenterClient";
        const string NodeId_Table1 = "NcCenter.Table1EstimatedRemainingSeconds";
        const string NodeId_Table2 = "NcCenter.Table2EstimatedRemainingSeconds";
        const string Urn = "urn:HOMAG:NcCenterServer";

        public InfeedTransportHandle()
        {
            Handle_Insert = new InsertInfoHandle();
            Handle_Search = new SearchInfoHandle();
            Handle_Modify = new ModifyInfoHandle();
            Handle_Common = new CommonHandle();
            Handle_Plc = new PlcHandle();
            OpcService_CNC = new OpcService_CNC();
        }

        public void Position_Transport(string Location)
        {
            Item Item_OrderState = null;
            Item Item_Reference = null;
            Item Item_Direction = null;
            var log = SerilogHandle.Logger_CT020;
            var Direction = 10;
            var mprName = string.Empty;
            var feature = string.Empty;
            float? width = 0;
            int RouteId = 0;
            bool width_Judgement = false;
            string TableMode = string.Empty;
            do
            {
            Start:
                Thread.Sleep(500);
                try
                {
                    if (Globle.isInfeedAreaActive)
                    {
                        switch (Location)
                        {
                            case "CT015":
                                Item_OrderState = Simosul.Item_T_CT020_OrderState;
                                Item_Reference = Simosul.Item_T_CT020_Reference;
                                Item_Direction = Simosul.Item_T_CT020_Direction;
                                log = SerilogHandle.Logger_CT020;
                                break;
                            default:
                                break;
                        }

                        var orderState = (int)(Handle_Plc.Read(Item_OrderState, "Int"));
                        if (!orderState.Equals((int)EnumOfOrderState.Plc请求数据)
                            && !orderState.Equals((int)EnumOfOrderState.Plc完成任务))
                        {
                            goto Start;
                        }

                        var Reference = Handle_Plc.Read(Item_Reference, "String").ToString();
                        OnlineInfoStruct onlineInfoStruct = Handle_Search.GetTransOnLineDetailInfo(Reference, Location);
                        if (onlineInfoStruct == null)
                        {
                            goto Start;
                        }

                        if (Globle.OpreationMode.Equals("Auto"))
                        {
                            mprName = onlineInfoStruct.boardInfo.MprName;
                            width = onlineInfoStruct.boardInfo.Width;
                            feature = onlineInfoStruct.boardInfo.Feature;
                        }
                        else
                        {
                            T_ProjectOrder t_ProjectOrder = new T_ProjectOrder();
                            t_ProjectOrder = Handle_Search.GetProjectOrderDetail();
                            if (t_ProjectOrder == null)
                            {
                                goto Start;
                            }
                            mprName = t_ProjectOrder.MprName;
                            width = t_ProjectOrder.Width;
                            feature = "0";
                        }
                        log.Information("Reference :" + Reference);
                        log.Information("orderState :" + orderState);

                        switch (orderState)
                        {
                            case (int)EnumOfOrderState.Plc完成任务:
                            Write2Plc:
                                ResultCode WriteFlag = Handle_Plc.Write(Item_OrderState, (int)EnumOfOrderState.CCT完成任务);
                                if (WriteFlag != ResultCode.Success)
                                {
                                    goto Write2Plc;
                                }
                                Handle_Modify.ModifyTransState(Reference);
                                break;
                            case (int)EnumOfOrderState.Plc请求数据:
                                try
                                {
                                Calculate_Path:
                                    var OnLineInfo = Handle_Search.GetTransOnLineInfo();
                                    var positionLookup = OnLineInfo.ToLookup(s => s.Location);
                                    switch (Location)
                                    {
                                        case "CT015":
                                            switch (width > 620 || feature.Equals("L"))
                                            {
                                                case true:
                                                    if (positionLookup["MI1_H330L"].FirstOrDefault() == null && Globle.isDRILLTEQActive_1)
                                                    {
                                                        RouteId = 3;
                                                        width_Judgement = true;
                                                        TableMode = "3";
                                                        goto SendMpr;
                                                    }
                                                    else
                                                    {
                                                        log.Information("Reference :" + Reference + "-> 超宽板件堵车,等待下次分配！");
                                                        Thread.Sleep(1000);
                                                        goto Calculate_Path;
                                                    }
                                                default:
                                                    switch (feature)
                                                    {
                                                        case "B":
                                                            //查看OPC反馈的数据
                                                            OpcService_CNC.OpcPara opcPara_table1 = new OpcService_CNC.OpcPara()
                                                            {
                                                                Description = Description,
                                                                Ip = Globle.CoreMachine1_IP,
                                                                NodeId = NodeId_Table1,
                                                                Urn = Urn,
                                                            };
                                                            OpcService_CNC.OpcPara opcPara_table2 = new OpcService_CNC.OpcPara()
                                                            {
                                                                Description = Description,
                                                                Ip = Globle.CoreMachine1_IP,
                                                                NodeId = NodeId_Table2,
                                                                Urn = Urn,
                                                            };
                                                            var table1 = OpcService_CNC.GetValue(opcPara_table1).ToString();
                                                            var table2 = OpcService_CNC.GetValue(opcPara_table2).ToString();
                                                            var table1Time = table1.Contains("null") ? 0 : int.Parse(table1);
                                                            var table2Time = table2.Contains("null") ? 0 : int.Parse(table2);

                                                            if (positionLookup["MI1_H330L"].FirstOrDefault() == null && Globle.isDRILLTEQActive_1)
                                                            {
                                                                RouteId = 1;
                                                                width_Judgement = false;
                                                                TableMode = "3";
                                                                goto SendMpr;
                                                            }
                                                            else if (positionLookup["MI1_H330R"].FirstOrDefault() == null && Globle.isDRILLTEQActive_1)
                                                            {
                                                                RouteId = 2;
                                                                width_Judgement = false;
                                                                TableMode = "4";
                                                                goto SendMpr;
                                                            }
                                                            else if (table1Time <= table2Time && Globle.isDRILLTEQActive_1)
                                                            {
                                                                RouteId = 1;
                                                                width_Judgement = false;
                                                                TableMode = "3";
                                                                goto SendMpr;
                                                            }
                                                            else if (table1Time > table2Time && Globle.isDRILLTEQActive_1)
                                                            {
                                                                RouteId = 2;
                                                                width_Judgement = false;
                                                                TableMode = "4";
                                                                goto SendMpr;
                                                            }
                                                            else
                                                            {
                                                                log.Information("Reference :" + Reference + "-> 堵车,等待下次分配！");
                                                                Thread.Sleep(1000);
                                                                goto Calculate_Path;
                                                            }
                                                        case "R":
                                                            if (positionLookup["MI1_H330R"].FirstOrDefault() == null && Globle.isDRILLTEQActive_1)
                                                            {
                                                                RouteId = 2;
                                                                width_Judgement = false;
                                                                TableMode = "4";
                                                                goto SendMpr;
                                                            }
                                                            else
                                                            {
                                                                log.Information("Reference :" + Reference + "-> 堵车,等待下次分配！");
                                                                Thread.Sleep(1000);
                                                                goto Calculate_Path;
                                                            }
                                                        default:
                                                            break;
                                                    }
                                                    break;
                                            }
                                            goto Plc;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    log.Error(ex.Message);
                                    goto Start;
                                }

                            SendMpr:
                                Handle_Insert.InsertJob2CNC(Globle.CoreMachine1_IP, Reference, 1, mprName, int.Parse(TableMode), log);
                                goto UpdateRoute;

                            UpdateRoute:
                                Direction = Handle_Modify.ModifyTransRouteId(Reference, RouteId, log, width_Judgement);
                                goto Plc;

                            Plc:
                                Handle_Plc.Write(Item_Direction, Direction);
                                Handle_Plc.Write(Item_OrderState, (int)EnumOfOrderState.CCT下发任务);
                                break;
                        }
                        goto Start;
                    }
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                    goto Start;
                }
            } while (true);
        }
    }
}